//
//  DepositStatusViewController.m
//  EDF
//
//  Created by p on 2019/7/16.
//  Copyright © 2019年 p. All rights reserved.
//

#import "DepositStatusViewController.h"
#import "EDHistoricalRecordCenterVC.h"
#import "LLWebViewController.h"
#define timeOut 8
@interface DepositStatusViewController ()<UITextViewDelegate>
@property (strong, nonatomic) UITextView * messageTextView;
@property (strong, nonatomic) NSString * message;
@property (strong, nonatomic) NSString * id;
@property (assign, nonatomic) NSInteger  index;
@end

@implementation DepositStatusViewController
-(void)refushData{
    
    [self getMoneyMobileAction:NO];
}
- (void)viewDidLayoutSubviews
{
    _messageTextView.mj_y = _lookButton.mj_y -60;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self getMoneyMobileAction:NO];
    
    _message = @"如您已付款,请不要取消申请,否则将导致无法到账!\n如多次支付失败，点此“取消”更换支付通道。";
    _messageTextView = [[UITextView alloc]initWithFrame:CGRectMake(20,
                                                                   
                                                                      _lookButton.mj_y,
                                                                     UIScreenWidth- 40,
                                                                     50)];
    // 设置属性
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    // 设置行间距
    paragraphStyle.paragraphSpacing = 2; // 段落间距
    paragraphStyle.lineSpacing = 1;      // 行间距
    NSDictionary *attributes = @{
                                 NSForegroundColorAttributeName:[UIColor blackColor],
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:_message attributes:attributes];
    [attrStr addAttributes:@{
                             NSLinkAttributeName:@"“取消”"
                             }
                     range:[_message rangeOfString:@"“取消”"]];
    _messageTextView.font = AutoFont(14);
    _messageTextView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor redColor]}; // 修改可点击文字的颜色
    _messageTextView.attributedText = attrStr;
    _messageTextView.editable = NO;
    _messageTextView.scrollEnabled = NO;
    _messageTextView.delegate = self;
    _messageTextView.backgroundColor = [UIColor clearColor];
    _messageTextView.textColor = RGBA(68, 68, 68, 1);
    _messageTextView.textAlignment = NSTextAlignmentCenter;
 
    [self.view addSubview:_messageTextView];
}
////使用GCD实现倒计时
//- (void)startTimeGCD {
//
//    WeakSelf
//    //创建队列(全局并发队列)
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
//    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
//    dispatch_source_set_event_handler(_timer, ^{
//        if(weakSelf.second >= timeOut){
//            //倒计时结束，关闭
//            dispatch_source_cancel(_timer);
//            //回到主线程更新UI
//            dispatch_async(dispatch_get_main_queue(), ^{
//
//                if (!weakSelf.isresh) {
//                    weakSelf.second = 0;
//                    [weakSelf startTimeGCD];
//                    [weakSelf getMoneyMobileAction];
//                }
//            });
//        }else{
//            dispatch_async(dispatch_get_main_queue(), ^{
//
//            });
//            weakSelf.second++;
//        }
//    });
//    dispatch_resume(_timer);
//}
// 其他方式修改
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    NSRange range = [_message rangeOfString:@"“取消”"];
    if (characterRange.location == range.location) {
         [self showLoadingAnimation];
        NSString  * AllGame = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"cancelDeposit"];
        [[SmileHttpTool sharedInstance] GET :AllGame parameters:@{@"id":self.id} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
            NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
            if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
       
                 [JMNotifyView showNotify:@"取消成功"  isSuccessful:NO];
                [self.navigationController popViewControllerAnimated:YES];
                
            }else{
                 [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
                
            }
            if (self.actionBtnClickBlock) {
                self.actionBtnClickBlock(102);
            }
             [self stopLoadingAnimation];
            
        } failure:^(id responseObject, NSError *error) {
             [self stopLoadingAnimation];
            
        }];
      
    }
    return YES;
}
- (void)getMoneyMobileAction:(BOOL)isShow
{
    NSString  * AllGame = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"moneyMobileAction"];
    WeakSelf
    if (isShow==YES) {
        //   [self showLoadingAnimation];
    }
 
    [[SmileHttpTool sharedInstance] GET :AllGame parameters:@{} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
        if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
            NSArray * activeDeposit = dict[@"data"][@"activeDeposit"];
            NSArray * passOnceDeposit =  dict[@"data"][@"passOnceDeposit"];
            NSArray * refuseDeposit =  dict[@"data"][@"refuseDeposit"];
            if (activeDeposit.count>0) { //审核中订单
                NSDictionary * dic = activeDeposit[0];
                id attachcode = dic[@"attachcode"];
                weakSelf.code.text = kFormat(@"%@", attachcode);
                weakSelf.id = dic[@"id"];
                weakSelf.index = 0;
//                weakSelf.messageTextView.text = @"如您已付款，请不要取消申请，否则将导致无法到账！如您支付失败，点此“取消”可重新提交";
            }else   if (passOnceDeposit.count>0) { //已完成订单
                
                NSDictionary * dic = passOnceDeposit[0];
                weakSelf.contentLab.text = @"你的存款订单号为:";
                weakSelf.messageTextView.text = @"恭喜您，您的款项已经成功充入至您的指定账户请您及时查收";
                id no = dic[@"no"];
                weakSelf.code.text = kFormat(@"%@", no);
                weakSelf.index = 1;
                 weakSelf.id = dic[@"id"];
                [weakSelf.lookButton setTitle:@"确认" forState:0];
                weakSelf.button.hidden = YES;
            }else if (refuseDeposit.count >0)//被拒
            {
                NSDictionary * dic = refuseDeposit[0];
                weakSelf.contentLab.text = @"你的存款订单号为:";
                NSString * remark = kFormat(@"%@\n%@",@"存款申请已被拒绝",dic[@"remark"]);
                weakSelf.messageTextView.attributedText = [WJUnit finderattributedString:remark attributedString:dic[@"remark"] color:[UIColor redColor] font:AutoFont(12)];
              
                id no = dic[@"no"];
                weakSelf.code.text = kFormat(@"%@", no);
                 weakSelf.id = dic[@"id"];
                [weakSelf.lookButton setTitle:@"确认" forState:0];
                weakSelf.button.hidden = YES;
                 weakSelf.index = 2;
            }
            
        }else{
            
             [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
        }
         [self stopLoadingAnimation];
        
    } failure:^(id responseObject, NSError *error) {
        
         [self stopLoadingAnimation];
    }];
}
- (IBAction)copyCode:(UIButton *)sender {
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = _code.text;
    [JMNotifyView showNotify:@"已复制粘贴板"  isSuccessful:YES];
}

- (IBAction)lookStatus:(id)sender {
    
    if (_index ==0)
    {
        [self getMoneyMobileAction:YES];
    }else if (_index ==1)
    {
        [self showLoadingAnimation];
          NSString  * passOnceMobileDeposit = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"passOnceMobileDeposit"];
        [[SmileHttpTool sharedInstance] GET :passOnceMobileDeposit parameters:@{@"id":self.id } origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
            NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
            if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
                if (self.actionBtnClickBlock) {
                    self.actionBtnClickBlock(101);
                }
                [self.navigationController popToRootViewControllerAnimated:YES];
                
            }else{
                
                [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
            }
            [self stopLoadingAnimation];
            
        } failure:^(id responseObject, NSError *error) {
            
            [self stopLoadingAnimation];
        }];
    }else
    {
        [self showLoadingAnimation];
        NSString  * refusedMobileDeposit = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"refusedMobileDeposit"];
        [[SmileHttpTool sharedInstance] GET :refusedMobileDeposit parameters:@{@"id":self.id } origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
            NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
            if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
                if (self.actionBtnClickBlock) {
                    self.actionBtnClickBlock(100);
                }
                  [self.navigationController popToRootViewControllerAnimated:YES];
                
            }else{
                
                [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
            }
            [self stopLoadingAnimation];
            
        } failure:^(id responseObject, NSError *error) {
            
            [self stopLoadingAnimation];
        }];
    }
  
}
//重新支付
- (IBAction)RePayment:(UIButton *)sender {
    
    [self showLoadingAnimation];
    NSString  * refusedMobileDeposit = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"reSubmitDeposit"];
    [[SmileHttpTool sharedInstance] GET :refusedMobileDeposit parameters:@{} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
        if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
               // UI更新代码
               [self open_UrlHandle:dict[@"data"]];
            });
//            LLWebViewController * webview = [[LLWebViewController alloc] init];
//            webview.urlStr = dict[@"data"];
//            webview.isType = 1;
//            webview.titleStr = @"存款";
//            webview.isWebGo = NO;
//            [self.navigationController pushViewController:webview animated:YES];
//
        }else{
            
            [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
        }
        [self stopLoadingAnimation];
        
    } failure:^(id responseObject, NSError *error) {
        
        [self stopLoadingAnimation];
    }];
    
}
-(void)open_UrlHandle:(NSString *)url{
    
    if (![url hasPrefix:@"http"]) {//是否具有http前缀
        url = [NSString stringWithFormat:@"http://%@",url];
    }
    if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]])
           {
               
               if (@available(iOS 10.0, *)) {
                   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
               } else {
                   // Fallback on earlier versions
               }
           }else
           {
               if (@available(iOS 10.0, *)) {
                   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
               } else {
                   // Fallback on earlier versions
               }
           }
    
}
@end
